import { Component, OnInit } from '@angular/core';
import { ModalController, NavController } from '@ionic/angular';
import { VideoModal } from '@modals/alarm-video/alarm-video';
import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';

@Component({
  selector: 'page-task',
  templateUrl: 'task.html',
  styleUrls: ['task.scss']
})
export class TaskPage implements OnInit {
  userId;
  alarmArresultLen = 0;
  alarmDatas = [];  // 告警数据
  eventDatas = [];  // 事件数据
  pageIndex = 1;    // 默认页码
  pageSize = 50;
  alarmLevel = 1;
  IsILastPage = false;
  alarmArresult = [];
  taskState = ['', '已确认', '已到场', '已处理', '已完成', '已完成'];
  totalSize = undefined;
  projectId;
  dealAlarmPermission = true;

  constructor(public navCtrl: NavController,
    private modalCtrl: ModalController,
    private dataService: DataService,
    private cache: CacheService
  ) {
    this.userId = this.cache.userinfo.userId;
    this.projectId = this.cache.currentProject ? this.cache.currentProject.projectId : 12;
  }

  ngOnInit() {
  }

  ionViewWillEnter() {
    this.getAlarm(this.projectId, null);
  }

  getAlarm(projectId, refresher) {
    this.dataService.getMyTask(projectId, this.userId).subscribe((val) => {
      console.log(val);
      const alarmArr = val.data || [];
      this.alarmArresultLen = alarmArr.length;
      this.alarmArresult = [];
      for (let i = 0; i < alarmArr.length; i += 30) {
        this.alarmArresult.push(alarmArr.slice(i, i + 30));
      }
      this.alarmDatas = this.getResultAlarmDatas(this.alarmArresult[this.pageIndex - 1]);
      if (refresher) {
        refresher.complete();
      }
    });
  }

  // 设备告警数据处理
  getResultAlarmDatas(arr) {
    arr.forEach((c) => {
      c.name = c.areaName + ' ' + c.deviceName;
      c.listType = (!c.isRestore && c.procState !== 0) ? '未恢复' : c.isRestore ? '已恢复' : '未处理';
      c.alarmTypeName = c.alarmTypeName;
      c.alarmReason = c.alarmValue + c.unit;
      c.type = 1;
      c.handleType = this.taskState[c.procState];
    });
    return arr;
  }
  // 事件分页加载
  loadData(type, infiniteScroll, refresher) {
    this.pageIndex++;
    this.getNextAlarm(infiniteScroll, refresher);
  }

  // 获取下一段设备告警
  getNextAlarm(infiniteScroll, refresher) {
    if (infiniteScroll) {
      if (!this.alarmArresult[this.pageIndex - 1]) {
        this.IsILastPage = true;
        setTimeout(() => {
          infiniteScroll.target.complete();
        }, 500);
      } else {
        setTimeout(() => {
          this.alarmDatas = [...this.alarmDatas, ...this.getResultAlarmDatas(this.alarmArresult[this.pageIndex - 1])];
          infiniteScroll.target.complete();
        }, 500);
      }
    }
    if (refresher) {
      refresher.complete();
    }

  }
  // 下拉刷新
  doRefresh(refresher) {
    this.IsILastPage = false;
    this.pageIndex = 1;
    this.getAlarm(this.projectId, refresher);
    setTimeout(() => {
      console.log('Async operation has ended');
      if (refresher) {
        refresher.complete();
      }
    }, 15000);
  }


  showPopup(data) {
    console.log(data);
    // this.navCtrl.push(AlarmDetailPage, {
    //     alarmInfo: data,
    //     title: '任务详情'
    //   });
    this.navCtrl.navigateForward(['tabs/my/AlarmDetailPage'], {
      queryParams: {
        data: data,
        title: '任务详情',
        alarmType: 'alarm',
        isLook: data.isMy && data.lastCancelUserId !== this.userId && data.procState !== 4 ? false : true,
        url: 'tabs/home/AlarmDetailPage/AlarmSolveComponent', // 子级处理描述跳转url
        callback: () => {// 返回回调，更新列表状态
          this.getAlarm(this.projectId, null);
        }
      }
    });
  }


  async watchVideo(data) {
    const config = {
      title: data.RoomName + ' ' + data.DeviceName,
      message: data.AlarmTypeName + data.AlarmText,
      preload: true,
      plugins: {
        poster: 'http://120.76.244.22:3000/android/1.5.9/poster.jpg'
      },
      sources: [{ src: data.VideoUrl, type: 'video/mp4', condition: Math.random() }]
    };

    const videoModal = await this.modalCtrl.create({
      component: VideoModal,
      componentProps: { config: config }
    });

    videoModal.present();
  }
  eww() {
    alert();
  }
}
